using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using CMS.Application.common.Interface;
using CMS.Application.Common.Interface;
using CMS.Application.RequestDto;
using CMS.Domain.Entity;
using Microsoft.AspNetCore.Mvc;

using SoftDemo.Api.Controllers;

namespace CMS.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class loginController : ControllerBase
    {
        private readonly IRepository<Register> _register;
        private readonly IRepository<Avatar> _Avatar;
        private readonly IRepository<Users> _Users;
        private readonly IRepository<Blog> _Blog;
        private readonly IRepository<BlogAllText> _BlogAllText;
        private readonly IRepository<BlogCollect> _BlogCollect;
        private readonly IRepository<Comment> _Comment;
        private readonly IRepository<AttentionAuthor> _AttentionAuthor;

        private readonly IFileUploadService _FileUploadService;

        public loginController(IRepository<AttentionAuthor> AttentionAuthor, IRepository<BlogAllText> BlogAllText, IRepository<Comment> Comment, IRepository<BlogCollect> BlogCollect, IFileUploadService FileUploadService, IRepository<Register> register, IRepository<Users> Users, IRepository<Blog> Blog, IRepository<Avatar> Avatar)
        {
            _AttentionAuthor = AttentionAuthor;

            _register = register;

            _Users = Users;

            _Blog = Blog;

            _Avatar = Avatar;

            _Comment = Comment;

            _BlogCollect = BlogCollect;

            _BlogAllText = BlogAllText;

            _FileUploadService = FileUploadService;

        }

        [HttpPost("/GetComment")]

        public async Task<object> Comment(CommentDto commentDto)
        {

            var comment = new Comment
            {

                UserId = commentDto.UserId,

                CommentText = commentDto.CommentText,

                BlogId = commentDto.BlogId,

                IsComment = false,

                CommentId = new Guid()

            };

            if (commentDto.IsComment)
            {
                comment.IsComment = true;

                comment.CommentId = commentDto.CommentId;

            }


            await _Comment.AddAsync(comment);

            return new
            {
                code = "200",

                data = "",

                msg = "评论成功"

            };

        }


        // 文章内容
        [HttpPost("/GetBlogContent")]
        public async Task<object> BlogContent(BlogContentDto blogContentDto)
        {

            // 实例化获取文件类
            var GetImgClass = new GetImg();

            // 获取完整内容
            var Text = _BlogAllText.Table.FirstOrDefault(x => x.BlogId == blogContentDto.Blogid);

            // 获取文章信息
            var blogData = _Blog.Table.FirstOrDefault(x => x.BlogId == blogContentDto.Blogid);

            // 返回是否点赞
            var IsCollect = _BlogCollect.Table.Where(x => x.UserId == blogContentDto.Userid && x.BlogId == blogContentDto.Blogid).ToList().Count() != 0;

            // 返回评论
            var CommentText = _Comment.Table.Where(x => x.UserId == blogContentDto.Userid && x.BlogId == blogContentDto.Blogid);

            // 返回获赞个数
            var collectCount = _BlogCollect.Table.Where(x => x.BlogId == blogContentDto.Blogid).ToList().Count();

            // 作者信息
            var AuthorData = await _Users.GetByIdAsync(blogData.AuthorId);

            // 返回作者头像
            var AuthorAvatar = await GetImgClass.GetImgFn(AuthorData.AvatarId, _FileUploadService);

            // 是否关注
            var IsAttention = _AttentionAuthor.Table.Where(x => x.AuthorId == blogData.AuthorId && x.UserId == blogContentDto.Userid).ToList().Count() != 0;


            return new
            {

                Text.BlogContent,

                blogData.BlogTitle,

                IsCollect,

                CommentText,

                collectCount,

                AuthorAvatar,

                IsAttention,

                AuthorData.UserName

            };

        }

        // 个人文章
        [HttpPost("/GetUserIndex")]
        public async Task<object> Userindex(UserindexDto userindexDto)
        {



            // 先按时间排序拿到当前用户所有文章
            var blogs = _Blog.Table.AsQueryable().Where(x => x.AuthorId == userindexDto.Id).OrderBy(time => time.UpdatedAt);

            //实例化封装后的分页静态类
            var sortPagingFn = new Sortpaging();

            // 调用封装后的分页函数
            var pageArr = await sortPagingFn.SortPaging(blogs, userindexDto.page, _FileUploadService, _Users, _BlogCollect, _Comment);



            return new
            {

                code = "200",

                data = new
                {

                    pageArr,

                },

                msg = "请求成功"

            };


        }

        // 首页
        [HttpPost("/GetIndex")]
        public async Task<object> Index(IndexDto indexDto)
        {


            // 先按时间排序拿到所有文章
            var blogs = _Blog.Table.AsQueryable().OrderBy(time => time.UpdatedAt);


            //实例化封装后的分页静态类
<<<<<<< HEAD
            var sortPagingFn = new Sortpaging( );
            
            // var sortPagingFn = new Sortpaging();
=======
            var sortPagingFn = new Sortpaging();
>>>>>>> 4f4e92fbdccc34aee86c6d66d8947c445451539c

            // 调用封装后的分页函数
            var pageArr = await sortPagingFn.SortPaging(blogs, indexDto.page, _FileUploadService, _Users, _BlogCollect, _Comment);



            return new
            {

                code = "200",

                data = new
                {

                    pageArr,

                },

                msg = "请求成功"

            };
        }


        //注册验证
        [HttpPost("/GetRegister")]
        public async Task<object> Register(RegisterDto registerDto)
        {


            // 获得用户名长度用于比较
            var NameLen = registerDto.Username.Length;

            if (NameLen > 8)
            {

                return new
                {

                    code = "400",

                    data = "",

                    msg = "用户名长度不可大于8"


                };

            }
            // 比较用户名是否存在
            var Name = _Users.Table.FirstOrDefault(x => x.UserName == registerDto.Username);

            if (Name != null)
            {

                return new
                {

                    code = "400",

                    data = "",

                    msg = "该用户名已存在！"

                }
                ;

            }
            // 比较密码长度
            var PasswordLen = registerDto.Password.Length;

            if (PasswordLen < 6)
            {
                return new
                {

                    code = "400",

                    data = "",

                    msg = "密码长度不可小于6"


                };
            }
            // 判断密码是否存在中文
            var IsCN = Regex.IsMatch(registerDto.Password, @"[\u4e00-\u9fa5]");

            if (IsCN)
            {

                return new
                {

                    code = "400",

                    data = "",

                    msg = "密码中不可存在中文！"


                };

            }


            // 判断邮箱和验证码是否正确
            var Code = _register.Table.FirstOrDefault(

                x => x.Email == registerDto.Email && x.AuthCode == registerDto.Code

   );

            var Newdate = DateTime.UtcNow;

            if (Code == null)
            {


                return new
                {

                    code = "400",

                    data = "",

                    msg = "验证码错误！"

                }
                ;

            }


            if ((Newdate - Code.UpdatedAt).TotalMinutes >= 5)
            {
                // 验证码过期删除数据
                await _register.DeleteAsync(Code.Id, true);

                return new
                {

                    code = "400",

                    data = "",

                    msg = "验证码已过期"

                };
            }

            // 我们默认头像表第一张为默认头像
            var avatarTable = _Avatar.Table.FirstOrDefault();

            // 将默认头像加入其中
            var fistAvatar = avatarTable.Id;

            // 注册成功添加到用户表中
            var users = new Users
            {

                Email = registerDto.Email,

                UserName = registerDto.Username,

                PassWord = registerDto.Password,

                IsAdministor = false,

                AvatarId = fistAvatar


            };

            await _Users.AddAsync(users);

            // 注册成功后会删掉注册表中的数据
            await _register.DeleteAsync(Code.Id, true);

            return new
            {

                code = "200",

                data = "",

                msg = "注册成功！！"

            };

        }


        //邮箱验证码发送
        [HttpPost("/GetEmail")]
        public async Task<object> Email(EmailDto emailDto)
        {
            // 判断邮箱是否已经被注册
            var IsEmail = _Users.Table.FirstOrDefault(x => x.Email == emailDto.Email);

            if (IsEmail != null)
            {

                return new
                {

                    code = "400",

                    data = "",

                    msg = "该邮箱已存在！！"

                };

            }


            // 判断是否是使用了QQ邮箱
            var IsQQ = Regex.IsMatch(emailDto.Email, "@qq.com");

            if (!IsQQ)
            {
                return new
                {

                    code = "400",

                    data = "",

                    msg = "目前仅支持QQ邮箱哦"

                };
            }

            // 调用封装后的发送邮件的静态类
            var EmailServer = new EmailServser(_register, _Users, emailDto.Email);

            var IsEmailServer = await EmailServer.ToEmail();

            return IsEmailServer;

        }

    }
}